<!DOCTYPE HTML>
<html>
<head>
<title>Ethiopia Family Medecine Assessment</title>
<script type="text/javascript" charset="utf-8" src="phonegap.0.9.5.js"></script>
<link rel="stylesheet" href="jquery.mobile-1.0a4.min.css" />
<script src="jquery-1.5.min.js"></script>
<script src="jquery.query-2.1.7.js"></script>
<script src="ethiopia.js"></script>
<script src="persistence.js" type="application/javascript"></script>
<script src="persistence.store.sql.js" type="application/javascript"></script>
<script src="persistence.store.websql.js" type="application/javascript"></script>
<script src="jquery.mobile-1.0a4.min.js"></script>
<script src="jquery.easytimepicker.js" type="application/javascript"></script>
<script src="jquery.easytimepicker.mobile.js" type="application/javascript"></script>
<!-- <script src="jquery.easytimepicker.combined.js" type="application/javascript"></script> -->
<link rel="stylesheet" href="ethiopia.css" />
</head>

<body>

<div data-role="page">

	<div data-role="header" data-theme="b" zdata-position="fixed">
		<h1>Activity</h1>
		<a href="activities.html" class='ui-btn-left ui-btn-back' data-icon='arrow-l' rel="external">Back</a>
		<div data-inline="true" class="ui-btn-right">
			<a  id="newclinical" data-role="button" data-icon="plus" >New clinical</a>
			<a id="newnonclinical" data-role="button" data-icon="plus" >New non clinical</a>
		</div>
		<p id="activityIdPlacer" class="activity-head"></p>
	</div><!-- /header -->
<!--	<div id="message" class="ui-body ui-body-e"></div>-->
	<div data-role="content" data-theme="b" id="activityview">
	<ul data-role="listview">
				<li id="date-time-li" data-role="list-divider">Clinical Encounter: </li>
				<li data-role="fieldcontain" >
					<div id="periods-content">
					</div>
					<form id="form-periods" action="javascript:;" >
						<fieldset data-role="fieldcontain"  >
							<div class="ui-grid-a" >
								<div class="ui-block-a">
									<label for="start">Start time</label>
									<a data-role="button" id="start-period-btn">Choose...</a>
									<div id="start-period-placer"></div>
									<!-- <a data-role="button"  id="to-now" data-inline="true" >set to now</a> -->
								</div>
								<div class="ui-block-b">
									<label for="end">End time</label>
									<a data-role="button" id="end-period-btn">Choose...</a>
									<div id="end-period-placer"></div>
									<input data-inline="true" data-role="button" data-icon="plus"  type="submit" id="submit-add-period" value="add period" />
								</div>
							</div>
						</fieldset>
					</form>
				</li>
	
				<li data-role="list-divider">Encounter Info</li>
				<li data-role="fieldcontain" >
					<fieldset data-type="horizontal" data-role="fieldcontain" class="ui-grid-a" >
						<div class="ui-block-a" data-inline="true"><h1>Follow-up visit</h1></div>
						<!--<div class="ui-block-a" data-inline="true">
							<label for="select-choice-followup" class="select">Follow-up visit</label>
						</div>-->
						<div class="ui-block-b" data-role="controlgroup" id="content-followup" >
						</div>
					</fieldset>
				</li>				
				<li data-role="fieldcontain" >
					<fieldset data-role="controlgroup"  data-type="horizontal" data-role="fieldcontain" class="ui-grid-a" >
							<div class="ui-block-a"><h1>Health promotion</h1></div>
							<div class="ui-block-b">
				         	<input type="radio" name="healthpromotion" id="healthpromotion-true" value="yes" />
				         	<label for="healthpromotion-true" >Yes</label>
				         	<input type="radio" name="healthpromotion" id="healthpromotion-false" value="no"  />
				         	<label for="healthpromotion-false" >No</label>
				         	 </div>
				    </fieldset>
				</li>
				<li data-role="fieldcontain" >
					<fieldset data-role="controlgroup"  data-type="horizontal" data-role="fieldcontain" class="ui-grid-a" >
						<div class="ui-block-a"><h1>Procedure performed</h1></div>
						<div class="ui-block-b">
				         	<input type="radio" name="procedureperformed" id="procedureperformed-true" value="yes" />
				         	<label for="procedureperformed-true" >Yes</label>
				         	<input type="radio" name="procedureperformed" id="procedureperformed-false" value="no"  />
				         	<label for="procedureperformed-false" >No</label>
			         	 </div>
			         	 <div data-role="fieldcontain">
							<textarea cols="35" rows="8" name="procedureperformedtxt-textarea" id="procedureperformedtxt-textarea"></textarea>
						</div>
				    </fieldset>
				</li>
				<li data-role="fieldcontain" >
					<fieldset data-type="horizontal" data-role="fieldcontain" class="ui-grid-a" >
						<div class="ui-block-a" data-inline="true">
							<h1>Presenting symptoms</h1>
							<div data-inline="true" >
								<a id="symptom-add" data-role="button" data-icon="plus" data-iconpos="notext">Add a symptom item...</a>
								<a id="symptom-editdel" data-role="button" data-icon="minus" data-iconpos="notext">Edit or delete a symptom item...</a>
							</div>
						</div>
						<div class="ui-block-b" data-role="controlgroup" id="content-symptom" >
						</div>
					</fieldset>
					<div>
						<form id="symptom-form-add" action="javascript:;" >
							<fieldset data-role="fieldcontain"  >
							    <label for="symptom-input-add">New symptom:</label>
							    <input type="text" name="symptom-input-add" id="symptom-input-add" value="" />
								<input type="submit" name="symptom-submit-add" id="symptom-submit-add" value="Add"  />
							</fieldset>
						</form>
					</div>
					<div id="symptom-editdel-content" >
					</div>
					<div id="placer-select-choice-symptom" class="activity-selections"></div>
				</li>
				<li data-role="fieldcontain" >
					<fieldset data-type="horizontal" data-role="fieldcontain" class="ui-grid-a" >
						<div class="ui-block-a" data-inline="true">
							<h1>Primary diagnosis</h1>
							<div data-inline="true" >
								<a id="diagnosis-add" data-role="button" data-icon="plus" data-iconpos="notext">Add a diagnosis item...</a>
								<a id="diagnosis-editdel" data-role="button" data-icon="minus" data-iconpos="notext">Delete a diagnosis item...</a>
							</div>
						</div>
						<div class="ui-block-b" data-role="controlgroup" id="content-diagnosis" >
						</div>
					</fieldset>
					<div>
						<form id="diagnosis-form-add" action="javascript:;" >
							<fieldset data-role="fieldcontain"  >
							    <label for="diagnosis-input-add">New diagnosis:</label>
							    <input type="text" name="diagnosis-input-add" id="diagnosis-input-add" value="" />
								<input type="submit" name="diagnosis-submit-add" id="diagnosis-submit-add" value="Add"  />
							</fieldset>
						</form>
					</div>
					<div id="diagnosis-editdel-content" >
					</div>
					<div id="placer-select-choice-diagnosis" class="activity-selections"></div>
				</li>
				<li data-role="list-divider">Disposition</li>
				<li data-role="fieldcontain" >
					<fieldset data-role="controlgroup"  data-type="horizontal" data-role="fieldcontain" class="ui-grid-a" >
							<div class="ui-block-a"><h1>Medication prescribed</h1></div>
							<div class="ui-block-b">
				         	<input type="radio" name="medicationprescribed" id="medicationprescribed-true" value="yes" />
				         	<label for="medicationprescribed-true" >Yes</label>
				         	<input type="radio" name="medicationprescribed" id="medicationprescribed-false" value="no"  />
				         	<label for="medicationprescribed-false">No</label>
				         	 </div>
				    </fieldset>
				</li>
				<li data-role="fieldcontain" >
					<fieldset data-role="controlgroup"  data-type="horizontal" data-role="fieldcontain" class="ui-grid-a" >
							<div class="ui-block-a"><h1>Test ordered</h1></div>
							<div class="ui-block-b">
				         	<input type="radio" name="testsordered" id="testsordered-true" value="yes" />
				         	<label for="testsordered-true" >Yes</label>
				         	<input type="radio" name="testsordered" id="testsordered-false" value="no"  />
				         	<label for="testsordered-false">No</label>
				         	 </div>
				    </fieldset>
				</li>
				<li data-role="fieldcontain" >
					<fieldset data-role="controlgroup"  data-type="horizontal" data-role="fieldcontain" class="ui-grid-a" >
							<div class="ui-block-a"><h1>Discharged home</h1></div>
							<div class="ui-block-b">
				         	<input type="radio" name="dischargedhome" id="dischargedhome-true" value="yes" />
				         	<label for="dischargedhome-true" >Yes</label>
				         	<input type="radio" name="dischargedhome" id="dischargedhome-false" value="no"  />
				         	<label for="dischargedhome-false">No</label>
				         	 </div>
				    </fieldset>
				</li>
				<li data-role="fieldcontain" >
					<fieldset data-role="controlgroup"  data-type="horizontal" data-role="fieldcontain" class="ui-grid-a" >
							<div class="ui-block-a"><h1>Admitted to hospital</h1></div>
							<div class="ui-block-b">
				         	<input type="radio" name="admittedtohospital" id="admittedtohospital-true" value="yes"  />
				         	<label for="admittedtohospital-true" >Yes</label>
				         	<input type="radio" name="admittedtohospital" id="admittedtohospital-false" value="no"  />
				         	<label for="admittedtohospital-false">No</label>
				         	 </div>
				    </fieldset>
				</li>
				<li data-role="fieldcontain" >
					<fieldset data-role="controlgroup"  data-type="horizontal" data-role="fieldcontain" class="ui-grid-a" >
							<div class="ui-block-a"><h1>Referred to specialist</h1></div>
							<div class="ui-block-b">
				         	<input type="radio" name="referredtospecialist" id="referredtospecialist-true" value="yes"  />
				         	<label for="referredtospecialist-true" >Yes</label>
				         	<input type="radio" name="referredtospecialist" id="referredtospecialist-false" value="no" />
				         	<label for="referredtospecialist-false">No</label>
				         	 </div>
				    </fieldset>
				    <div id="container-referredreason">
					    <fieldset data-type="horizontal" data-role="fieldcontain" class="ui-grid-a" >
							<div class="ui-block-a" data-inline="true">
								<h1>&nbsp;&nbsp;Reason</h1>
								<div data-inline="true" >
									<a id="referredreason-add" data-role="button" data-icon="plus" data-iconpos="notext">Add a reason item...</a>
									<a id="referredreason-editdel" data-role="button" data-icon="minus" data-iconpos="notext">Edit or Delete a reason item...</a>
								</div>
							</div>
							<div class="ui-block-b" data-role="controlgroup" id="content-referredreason">
							</div>
						</fieldset>
						<div>
							<form id="referredreason-form-add" action="javascript:;" >
								<fieldset data-role="fieldcontain"  >
								    <label for="referredreason-input-add">New reason:</label>
								    <input type="text" name="referredreason-input-add" id="referredreason-input-add" value="" />
									<input type="submit" name="referredreason-submit-add" id="referredreason-submit-add" value="Add"  />
								</fieldset>
							</form>
						</div>
						<div id="referredreason-editdel-content" >
						</div>
						<div id="placer-select-choice-referredreason" class="activity-selections"></div>
					</div>
				</li>
				<li data-role="list-divider">COMPLETE</li>
				<li data-role="fieldcontain" >
					<fieldset data-role="controlgroup"  data-type="horizontal" data-role="fieldcontain" class="ui-grid-a" >
						<div class="ui-block-a"><h1>Complete ?</h1></div>
						<div class="ui-block-b">
				         	<input type="radio" name="complete" id="complete-true" value="yes" />
				         	<label for="complete-true" >Yes</label>
				         	<input type="radio" name="complete" id="complete-false" value="no"  />
				         	<label for="complete-false">No</label>
			         	 </div>
				    </fieldset>
				</li>
				<li id="complete-light"></li>
	</ul>
	</div>
</div>
</body>


<script>
initApp(renderActivityView);

var selectSingleOnly = ["followup"];

function updateAndBindBoolField(entity,field){
	var val = persistence.get(entity, field);
	$("#"+field+"-"+val).attr('checked', true).checkboxradio("refresh");
	$("#"+field+"-"+!val).attr('checked', false).checkboxradio("refresh");

	// for "procedureperformed" field
	if(field.indexOf("procedureperformed")>=0){
		if(val==true){
			$("#"+field+"txt-textarea").show();
		}else{
			$("#"+field+"txt-textarea").hide();
		}
	}

	// for Reasons Referred
	if(field.indexOf("referredtospecialist")>=0){
		if(val==true){
			$("#container-referredreason").show();
		}else{
			$("#container-referredreason").hide();
		}
	}

	$("#"+field+"-"+true).bind("change",function(){
		persistence.set(entity, $(this).attr("name"), true);
		persistence.flush();
		if(field=="complete"){
			updateActivityHead();
		}
		// for "procedureperformed" field
		if(field.indexOf("procedureperformed")>=0){
			$("#"+field+"txt-textarea").show();
		}
		// for Reasons Referred
		if(field.indexOf("referredtospecialist")>=0){
			$("#container-referredreason").show();
		}
	});
	$("#"+field+"-"+false).bind("change",function(){
		persistence.set(entity, $(this).attr("name"), false);
		persistence.flush();
		if(field=="complete"){
			updateActivityHead();
		}
		// for "procedureperformed" field
		if(field.indexOf("procedureperformed")>=0){
			$("#"+field+"txt-textarea").hide();
		}
		// for Reasons Referred
		if(field.indexOf("referredtospecialist")>=0){
			$("#container-referredreason").hide();
		}
	});
}

function updateAndBindTextField(entity,field){
	var val = persistence.get(entity, field);
	$("#"+field+"-textarea").val(val);

	$("#"+field+"-textarea").bind("focusout",function(){
		console.log($(this).val());
		persistence.set(entity, field, $(this).val());
		persistence.flush();
	});
}

function renderOption(entityNameLC,propid,propval,propremoved){
	var strRemove = "";
	if(propremoved){
		strRemove="(DISABLED) ";
	}
	var str = '<p id="choosen-'+propid+'">'+ strRemove + propval + '</p>';
	$("#placer-select-choice-"+entityNameLC).append(str);
}

function renderSelectView(entityName,entityNameLC,colsLive,callback){
	var clinical = activity.clinical;
		$("#placer-select-choice-"+entityNameLC).empty();
		$("#select-choice-"+entityNameLC+" option").each(function () {
	   	   if($(this).attr("selected")){
	    	   var propforlistid=$(this).attr("value");
	    	   var propval = $(this).text();
	    	   PropForList.load(propforlistid,function(propforlist){
					var entity = eval("new "+entityName+"({num:0});");
					persistence.add(entity);
					entity.propforlist=propforlist;
					colsLive.add(entity);
					persistence.flush(function(){
						renderOption(entityNameLC,propforlistid,propval,propforlist.removed);
					});
	    	   });
	   	   }

		});
		if (callback) callback();

}

function buildColName(entityNameLC){
	var colname=entityNameLC;
	if(colname.charAt(colname.length-1)!='s'){
		colname+='s';
	}
	return colname;
}

function buildEntityNameLC(entityName){
	var entityNameLC = entityName.toLowerCase();
	return entityNameLC;
}

function renderSelect(entityName,attachLive,callback){
	var clinical = activity.clinical;
	var entityNameLC = buildEntityNameLC(entityName);
	var selectId='select-choice-'+entityNameLC;
	var multipleStr;
	
	if (jQuery.inArray(entityNameLC, selectSingleOnly) < 0){ multipleStr = 'multiple="multiple"'; }
	
	//for ex, get referredreason only list
	PropForList.all().filter("kind", "=" , entityNameLC).order("value").list(function(propForLists){
		$('#content-'+entityNameLC).empty();
		var str = '<select  data-role="none" name="'+selectId+'" id="'+selectId+'" ' +multipleStr+ ' data-native-menu="'+datanativemenu+'"></select>'
		$('#content-'+entityNameLC).append(str);
		$('#'+selectId).append( '<option value="null" disabled="disabled">Choose...</option>');
		for(var i =0;i<propForLists.length;i++){
			propforlist = propForLists[i];
			if(!propforlist.removed){
				$('#'+selectId).append( '<option id="'+propforlist.id+'" value="'+propforlist.id+'">'+propforlist.value+'</option>');
			}
		}

		//retrieveing colname (should be with a s at the ends.. but not for diagnosis)
		var colname=buildColName(entityNameLC);

		var cols = persistence.get(clinical,colname);
		cols.list(function(dbPropForLists){
			for(var i =0;i<dbPropForLists.length;i++){
				var res = dbPropForLists[i];
				var propforlist = res.propforlist;
				var propval = propforlist.value;
				renderOption(entityNameLC,propforlist.id,propval,propforlist.removed);
				$('#'+propforlist.id).attr("selected","selected");
				//refresh dyn options...

			}
			//$('#'+selectId).selectmenu('refresh', true);
			//$('#select-choice-'+entityNameLC).page();

			$('#content-'+entityNameLC).page();
			//$('#'+selectId).page();
			//$('#'+selectId).selectmenu('refresh', true);

			if(attachLive){
				var colsLive = cols;
				setSelLiveOnChange(selectId,entityName,entityNameLC,colsLive,function(){});
			}

			if (callback) callback();
		});
	});
}

function setSelLiveOnChange(selectId,entityName,entityNameLC,colsLive,callback){
	$('#'+selectId).live("change",function () {
		 // we destroy all the references on any change on the list
		 colsLive.destroyAll(function(){
			 renderSelectView(entityName,entityNameLC,colsLive,callback);
		 });
	  });
}

function renderActivityContentView() {
	showDefaultMessage();
	//Binding activity core data
	updateAndBindBoolField(activity,"complete");

	// automatically retrieve fields of clinical and binding them to the UI checkboxes
	var clinical = activity.clinical;
	var fields = persistence.getEntityMeta().Clinical.fields;
	for(var field in fields) {
        var fieldType = fields[field];
        // BOOL fields only
        if(fieldType=="BOOL"){
        	updateAndBindBoolField(clinical,field);
        }
        if(fieldType=="TEXT"){
        	updateAndBindTextField(clinical,field);
        }
     }

	// entities For Select to update
	var entitiesFS=["ReferredReason","Diagnosis","Symptom", "Followup"];
	for(var e=0;e<entitiesFS.length;e++) {
		var entityName = entitiesFS[e];
		renderSelect(entityName,true,function(){});
		renderFormAddView(entityName,function(){});
		renderEditDelView(entityName,function(){});
	}

	renderDateView();
	updateActivityHead();
	hideMessage();
}

function buildCompletionLight(){
	var completeStr = '<span class="ui-icon-complete-' + activity.complete;
	if(!activity.complete) {
		completeStr += '">incomplete</span>';
	}else{
		completeStr += '">_complete_</span>';
	}
	return completeStr;
}

function updateActivityHead(){
	$("#activityIdPlacer").text("Clinical #"+activity.num +" / "+formatDate(activity.day)).append(" / "+buildCompletionLight());
	$("#complete-light").empty();
	$("#complete-light").append(buildCompletionLight());
}

var activityId;
var activity;
var datanativemenu;

function renderActivityView(){
	if (typeof device  != "undefined"){
		document.addEventListener("backbutton", function(){goToPage("activities.html");}, false);
	}
	activityId = $.query.get('act');
	var datanativemenu=true;
	Activity.all().filter("id", '=', activityId).prefetch("clinical").one(function(result){
		activity = result;
		persistence.add(activity);
		renderActivityContentView();
	});
}

$('#newclinical').bind('click',function() {
	newClinical(function(activity){
		var str = "activity.html?act=" + activity.id;
		window.location.href = str;
	});
});

$('#newnonclinical').bind('click',function() {
	newNonClinical(function(activity){
		var str = "ncactivity.html?act=" + activity.id;
		window.location.href = str;
	});
});

function renderEditDelUl(entityNameLC) {
	var contentId =entityNameLC+'-editdel-content';
	PropForList.all().filter("kind", "=" , entityNameLC).order("value").list(function(dbPropForLists){
		$('#'+contentId).empty();
		var str ='<ul data-role="listview" data-inset="true" id="'+contentId+'-ul">';
		str +='<li data-role="list-divider">Edit or delete from list:</li>';
		for(var i =0;i<dbPropForLists.length;i++){
			var propforlist = dbPropForLists[i];
			var formId = entityNameLC+'-form-editdel-'+propforlist.id;
			if(!propforlist.removed){
				str +='<li data-role="fieldcontain" >';
				str +='<form id="'+formId+'" action="javascript:;" >';
				str +='<fieldset data-role="fieldcontain" data-inline="true"  data-type="horizontal" >';
				str +='<a id="del-'+propforlist.id+'" data-role="button" data-icon="delete" data-iconpos="notext">del</a>';
				str +='&nbsp;<input data-inline="true" type="text" name="'+entityNameLC+'-input-edit-'+propforlist.id+'" id="'+entityNameLC+'-input-edit-'+propforlist.id+'" value="'+propforlist.value+'" />';
				str +='&nbsp;<input data-role="button" data-icon="check" data-iconpos="notext" type="submit" name="'+entityNameLC+'-submit-edit-'+propforlist.id+'" id="symptom-submit-edit-'+propforlist.id+'" />';
				str +='</fieldset>';
				str +='</form>'
				str +='</li>';
				var inputTextId=entityNameLC+'-input-edit-'+propforlist.id;
				setFormDelEditLive(entityNameLC,contentId,formId,propforlist.id,inputTextId);
			}
		}
		str +='</ul>';
		$('#'+contentId).append(str);
		$('#'+contentId+'-ul').page();
	});
}

function setBindEditDel(entityNameLC){
	var contentId =entityNameLC+'-editdel-content';
	$("#"+contentId).hide();
	$('#'+entityNameLC+'-editdel').bind('click',function() {
		$("#"+contentId).toggle();
		renderEditDelUl(entityNameLC);
	});
}

function setFormDelEditLive(entityNameLC,contentId,formId,propForListId,inputTextId){
	$('#'+formId).die("submit");
	$('#'+formId).live("submit",function(){
		PropForList.all().filter("id","=",propForListId).one(function(propForList){
			persistence.add(propForList);
			propForList.value=$('#'+inputTextId).attr("value");
			persistence.flush(function(){
				$("#"+contentId).hide();
				$('#'+contentId).empty();
				$('#'+propForListId).text(propForList.value);
				$('#choosen-'+propForListId).text(propForList.value);
			});
		});
	});

	$('#del-'+propForListId).die("click");
	$('#del-'+propForListId).live("click",function(){
		if(confirm("This will disable this " + entityNameLC + " from the select box, are you sure ?")){
			PropForList.all().filter("id","=",propForListId).one(function(propForList){
				persistence.add(propForList);
				propForList.removed=true;
				persistence.flush(function(){
					$("#"+contentId).hide();
					$('#'+contentId).empty();
					$('#'+propForListId).remove();
					var strToApp = $('#choosen-'+propForListId).text();
					$('#choosen-'+propForListId).text('(DISABLED) '+strToApp);
				});
			});
		}
	});

}

function renderEditDelView(entityName,callback){

	var entityNameLC = buildEntityNameLC(entityName);

	setBindEditDel(entityNameLC);


	if (callback) callback();
}

function setBindFormToggle(entityNameLC){
	$('#'+entityNameLC+'-add').bind('click',function() {
		$('#'+entityNameLC+'-form-add').toggle();
	});
}

function renderFormAddView(entityName,callback){
	var entityNameLC = buildEntityNameLC(entityName);
	var formId= entityNameLC+'-form-add';

	$('#'+formId).hide();

	setBindFormToggle(entityNameLC);

	setFormAddLive(formId,entityName,entityNameLC);

	if (callback) callback();
}


function setFormAddLive(formId,entityName,entityNameLC){

	$('#'+formId).submit(function(){
		$("#placer-select-choice-"+entityNameLC).empty();
		var inputValue = $('#'+entityNameLC+'-input-add').attr("value").toLowerCase();
		var propForList = newPropForList(entityNameLC,inputValue);
		PropForList.all().filter("devuid", '=', propForList.devuid).filter("kind", '=', propForList.kind).filter("value", '=', propForList.value).one(function(prop){
			// If item exists already than do an update, otherwise it must be added
			if(prop){
				persistence.set(prop, "removed", 0);
				console.log('properly re-enabled');
			}
			else {
			 	persistence.add(propForList);
			}

			persistence.flush(function(){
				PropForList.all().filter("value","=",inputValue).one(function(propForList){
					$('#'+formId).hide();
					var colname = buildColName(entityNameLC);
					var cols = persistence.get(activity.clinical,colname);
					cols.filter("propforlist","=",propForList.id).one(function(ent){
						var entity =ent;
						if(!entity){
							entity = eval("new "+entityName+"({num:0});");
						}
						persistence.add(entity);
	
						entity.propforlist=propForList;
						cols.add(entity);
						persistence.flush(function(){
							renderSelect(entityName,false,function(){
								$('#'+entityNameLC+'-input-add').attr("value","");
								$('#'+entityNameLC+'-add').focus();
							});
						});
					});
				});
			});
			return false;
		});		
	});
}

function renderStartInputTime(){
	$("#start-period-btn").remove();
	$("#start-period-placer").append('<input type="time" name="start-period" id="start-period" data-interval="1" data-display-24hour="false" data-value-24hour="true" data-start-time="360" data-end-time="1200" data-native-menu="true"/>');
	$("#start-period-placer").page();
}


function renderEndInputTime(){
	$("#end-period-btn").remove();
	$("#end-period-placer").append('<input type="time" name="end-period" id="end-period" data-interval="1" data-display-24hour="false" data-value-24hour="true" data-start-time="360" data-end-time="1200" data-native-menu="true"/>');
	$("#end-period-placer").page();
}

function renderDateView(){

	$("#date-time-li").append(" " + activity.day.toDateString());

	$("#start-period-btn").bind('click',function() {
		showDefaultMessage();
		renderStartInputTime();
		hideMessage();
	});

	$("#end-period-btn").bind('click',function() {
		showDefaultMessage();
		renderEndInputTime();
		hideMessage();
	});

	$("#to-now").live('click',function() {
		showDefaultMessage();
		if( (!$("#start-period").val()) ){
			renderStartInputTime();
		}
		if( (!$("#end-period").val()) ){
			renderEndInputTime();
		}
		var now = new Date();
		var timeStr = formatTime(now);
		$("#start-period").val(timeStr);
		$("#end-period").val(timeStr);
		hideMessage();
	});

	$("#submit-add-period").live('click',function() {
		if( (!$("#start-period").val()) || (!$("#end-period").val()) ){
			alert("Before, please choose a start and an end time for period.");
			return;
		}
		var strStartTime = $("#start-period").val();
		var startTimeArr = strStartTime.split(":");
		var startH = parseInt(startTimeArr[0],10);
		var startM = parseInt(startTimeArr[1],10);

		var currActDate = activity.day;
		var currActDateMilli = currActDate.getTime();
		var startDateForDB = new Date(currActDateMilli + 3600000*startH + 60000*startM);

		var strEndTime = $("#end-period").val();
		var endTimeArr = strEndTime.split(":");
		var endH = parseInt(endTimeArr[0],10);
		var endM = parseInt(endTimeArr[1],10);
		var endDateForDB = new Date(currActDateMilli + 3600000*endH + 60000*endM);
		// add one more day if endtime is smaller than starttime (for midnight situations...)
		var keepGoing = true;
		if(endDateForDB<startDateForDB){
			endDateForDB = new Date(currActDateMilli + 3600000*endH + 60000*endM + 86400000);
			keepGoing = confirm("End Time is before Start Time, please correct and continue.");
			keepGoing = false;	// do not add if start & end times are inconsistent
		}

		if(keepGoing){
			var period = new Period({start: startDateForDB,end: endDateForDB});
			activity.periods.add(period);
			persistence.flush(function(){
				updatePeriodMinMax(renderPeriodView());
			});
		}

	});

	updatePeriodMinMax(renderPeriodView());
}

function updatePeriodMinMax(callback){
	// retrieving min date for activity
	activity.periods.order('start',true).limit(1).one(function(periodStartMin){
		if(periodStartMin!=null){
			activity.veryfirsttime = periodStartMin.start;
		}else{
			activity.veryfirsttime = activity.creationdate;
		}
		// retrieving max date for activity
		activity.periods.order('end',false).limit(1).one(function(periodEndMax){
			if(periodEndMax!=null){
				activity.veryendtime = periodEndMax.end;
			}else{
				activity.veryendtime = null;
			}
			persistence.flush(function(){
				if (callback) callback();
			});
		});
	});
}


function setLivePeriodDel(periodId){
	$('#del-'+periodId).die("click");
	$('#del-'+periodId).live("click",function(){
		activity.periods.filter("id","=",periodId).one(function(period){
			activity.periods.remove(period);
			persistence.remove(period);
			persistence.flush(function(){
				updatePeriodMinMax(renderPeriodView());
			});
		});
	});
}

function renderPeriodView(){
	activity.periods.order('start',false).list(function(periods){
		var str ='<div id="periods-content-ul">';
		str +='<ul data-role="listview" data-inset="true" data-role="fieldcontain">';
		for(var i=0;i<periods.length;i++){
			var period = periods[i];
			var periodEndStr = '__:__';
			if(period.end){
				periodEndStr = formatTime(period.end);
			}
			str +='<li>';
			str +='<div class="ui-grid-b">';
			str +='<div class="ui-block-a"><a data-role="button" data-icon="delete" data-iconpos="notext" id="del-'+period.id+'">del</a></div>';
			str +='<div class="ui-block-b"><h2>'+formatTime(period.start)+' - '+periodEndStr+'</h2></div>';
			str +='</div>';
			str +='</li>';

			setLivePeriodDel(period.id);

		}
		str +='</ul>';
		str +='</div>';

		$("#"+"periods-content").empty();
		if(periods.length==0){
			str = '<p class="activity-selections">No periods for this activity, please choose...</p>';
		}
		$("#"+"periods-content").append(str);
		$("#"+"periods-content-ul").page();
	});
}


</script>
</html>